#include"DetectHash.h"
#include "prime.h"
#include <iostream>
using namespace std;


int DetectHash::findpos(int x)
{
	int offset = 1;
	int pos = myhash(x);

	while (m_hashtable[pos].state != HashEntry::EMPTY &&
		m_hashtable[pos].value != x)
	{
		pos += offset;
		offset += 2;

		//pull back
		if (pos >= tablesize)
			pos -= tablesize;

	}

	cout << "pos =  " << pos << endl;
	return pos;

}

void DetectHash::insert(int x)
{
	cout << "insert " << x << endl;


	int curpos = findpos(x);

	m_hashtable[curpos] = HashEntry(x, HashEntry::ACTIVE);

	++currsize;
	
	if (currsize >= tablesize / 2)
		rehash();
}


void DetectHash::desc()
{


	for (int i = 0; i < tablesize; ++i)
	{
		cout << i << ": " << m_hashtable[i].value <<" " << state2str(m_hashtable[i].state) << endl;
	}


}

bool DetectHash::remove(int x)
{

	cout << "remove " << x << endl;

	int curpos = findpos(x);

	if (m_hashtable[curpos].state != HashEntry::ACTIVE)
		return false;

	m_hashtable[curpos].state = HashEntry::DELETED;
	return true;
}

void DetectHash::rehash()
{
	cout << "rehash" << endl;

	vector<HashEntry> old = m_hashtable;
	tablesize = nextPrime(2 * tablesize);
	
	
	m_hashtable = vector<HashEntry>(tablesize);

	for (int i = 0; i < old.size(); ++i)
	{
		if (old[i].state == HashEntry::ACTIVE)
		{
			insert(old[i].value);
		}
	}


}